<template>
<!--面包屑-->
<div style="margin-bottom: 30px">
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>
      <router-link to="/Materials/ShowMaterialRequisition">物资领用</router-link>
    </el-breadcrumb-item>
    <el-breadcrumb-item>物资领用列表</el-breadcrumb-item>
  </el-breadcrumb>
</div>

  <!--查询条件-->
  <div style="margin-bottom: 30px;">
    领用人：<el-input v-model="form.Recipient" placeholder="请输入领用人" style="width: 240px;"></el-input>&nbsp;&nbsp;
    领用日期：<el-date-picker v-model="form.CollectionDate" type="date" placeholder="请选择领用日期" value-format="YYYY-MM-DD"/>&nbsp;&nbsp;
    审批状态：
  <el-select v-model="form.ApprovalStatus" placeholder="请选择" style="width: 240px;">
    <el-option label="全部" value="" />
    <el-option v-for="item in ApprovalStatusData" :key="item.enumId" :label="item.enumName" :value="item.enumId" />
  </el-select> &nbsp;&nbsp; &nbsp;&nbsp; 

    <br/>
    <br/>
    审批人：<el-input v-model="form.Approver" placeholder="请输入审批人" style="width: 240px;"></el-input>&nbsp;&nbsp;
    
    <el-button type="primary" @click="getStoreList">查询</el-button>
    <el-button @click="reset">重置</el-button>
    <br/>
    <br/>
    <el-button type="primary" @click="router.push('AddMaterialRequisition')">新增</el-button>&nbsp;&nbsp;
    <el-button type="danger" @click="deletedRange()">批量删除</el-button>
  </div>
  
  <!--物资列表-->
  <div>
    <el-table :data="StoreData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" />
      <el-table-column prop="title" label="标题" align="center" />
      <el-table-column prop="usageDescription" label="用途描述" align="center" width="160px" />
      <el-table-column prop="recipient" label="领用人" align="center" />
      <el-table-column prop="collectionDate" label="领用时间" align="center" width="135px" >
        <template v-slot="scope">
          {{ scope.row.collectionDate.substr(0,16).replace("T"," ") }}
        </template>
      </el-table-column>
      <el-table-column prop="materialRequisitNotes" label="备注" align="center" />
      <el-table-column prop="createdDate" label="创建时间" align="center" width="135px" >
        <template v-slot="scope">
          {{ scope.row.createdDate.substr(0,16).replace("T"," ") }}
        </template>
      </el-table-column>
      <el-table-column prop="approvalStatus" label="审批状态" align="center" >
        <template v-slot="scope">
          <el-tag type="primary" v-if="scope.row.approvalStatus==10">待提交</el-tag>
          <el-tag type="warning" v-if="scope.row.approvalStatus==20">待审批</el-tag>
          <el-tag type="success" v-if="scope.row.approvalStatus==30">已通过</el-tag>
          <el-tag type="danger"  v-if="scope.row.approvalStatus==40">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="approver" label="审批人" align="center" />
      <el-table-column label="操作" align="center" width="202px" >
        <template v-slot="scope">
          <el-link type="primary" target="_blank" v-if="scope.row.approvalStatus==10" @click="router.push('ReverseMaterialRequisition?materialRequisitionId='+scope.row.materialRequisitionId)" >编辑</el-link>&nbsp;&nbsp;
          <el-link type="primary" target="_blank" v-else-if="scope.row.approvalStatus==40" @click="router.push('ReverseMaterialRequisition?materialRequisitionId='+scope.row.materialRequisitionId)" >编辑</el-link>&nbsp;&nbsp;
          <span v-else></span>&nbsp;&nbsp;
          <el-link type="danger" target="_blank" @click="del(scope.row.materialRequisitionId)" >删除</el-link>&nbsp;&nbsp;
          <el-link type="primary" target="_blank" @click="checkInfo(scope.row.materialRequisitionId)" >查看</el-link>&nbsp;
          <el-link type="primary" target="_blank" v-if="scope.row.approvalStatus==10"      @click="UpdateStatus(scope.row.materialRequisitionId,10)">提交审批</el-link>&nbsp;
          <el-link type="primary" target="_blank" v-else-if="scope.row.approvalStatus==40" @click="UpdateStatus(scope.row.materialRequisitionId,40)">重新提交</el-link>&nbsp;
          <span v-else></span>
        </template>
      </el-table-column>
    </el-table>
  </div>
  
  <!--分页-->
  <div>
    <table>
    <thead></thead>
    <tbody>
      <tr>
        <td>
          <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[15, 20, 25, 30]" :background="true" layout="total,slot, sizes" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <span>
              ，每页{{ form.pageSize }}条，当前第:{{ form.pageIndex }}/{{ form.pageCount }}页
            </span>
          </el-pagination>
        </td>
  
        <td>
          <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[15, 20, 25, 30]" :background="true" layout="slot, prev, pager, next" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <el-button type="primary" class="btn-prev" @click="handleCurrentChange(1)" :disabled="form.pageIndex==1">首页</el-button>
          </el-pagination>
        </td>
  
        <td>
          <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[15, 20, 25, 30]" :background="true" layout="slot, jumper" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            <el-button type="primary" class="btn-prev" @click="handleCurrentChange(form.pageCount)" :disabled="form.pageIndex==form.pageCount">尾页</el-button>
          </el-pagination>
        </td>
      </tr>
    </tbody>
  </table>
  </div>

    <!--对话框--查看详情-->
    <el-dialog v-model="centerDialogVisible" title="物资领用详情信息" width="500" center>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>

<el-form-item label="标题" prop="title">
  <el-input v-model="form.title" placeholder="请输入领用标题" disabled />
</el-form-item>

<el-form-item label="用途描述" prop="usageDescription">
  <el-input v-model="form.usageDescription" :rows="3" type="textarea" placeholder="请输入用途描述" disabled />
</el-form-item>

<el-form-item label="备注" prop="materialRequisitNotes">
  <el-input v-model="form.materialRequisitNotes" :rows="3" type="textarea" placeholder="请输入备注" disabled />
</el-form-item>

<el-form-item label="选择领用物品" prop="materialStoreId">
  <el-select v-model="form.materialStoreId" placeholder="请选择要领用的物品" style="width: 430px;" disabled>
    <el-option v-for="item in StoreIdData" :key="item.materialStoreId" :label="item.nameOfGoods" :value="item.materialStoreId"></el-option>
  </el-select>
</el-form-item>

<div style="margin-left: 95px;" v-if="sotreDataListByIdData.length>0">
  <table border style="border-collapse: collapse;width: 100%;background-color:gainsboro;text-align: center;" >
  <thead></thead>
  <tbody>
    <tr>
      <td>货物名称</td>
      <td>类型</td>
      <td>材质</td>
      <td>规格</td>
      <td>产地</td>
      <td>仓库数量</td>
      <td>领用数量</td>
      <td>操作</td>
    </tr>

    <tr v-for="(item,index) in sotreDataListByIdData" :key="item.materialStoreId">
      <td>{{ item.nameOfGoods }}</td>
      <td>{{ item.materialStoreType }}</td>
      <td>{{ item.material }}</td>
      <td>{{ item.specifications }}</td>
      <td>{{ item.countryName }}</td>
      <td>{{ item.number }}</td>
      <td>
        <el-input v-model="NumberArray[index]" placeholder="请输入领用数量" disabled></el-input>
      </td>
    </tr>
  </tbody>
</table>
</div>
</el-form>
  </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { reactive, ref, onMounted, computed } from 'vue'
  import axios from 'axios';
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  import {useRoute,useRouter} from 'vue-router'
  
  const route = useRoute();
  const router = useRouter();
  const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
  const centerDialogVisible = ref(false)
  
  //定义数量数组
const NumberArray:any=ref([])
  onMounted(() => {
    //获取审批状态枚举反射
    getApprovalStatus()

    //物资列表
    getStoreList()
      //入库列表==>查询id
    getStoreIdList()
  })

//获取审批状态枚举反射
const ApprovalStatusData:any=ref([])
const getApprovalStatus=()=>{
  axios.get('/mread/api/ShowMaterialStore/GetApprovalStatusEnum').then(res=>{
    //console.log(res);
    ApprovalStatusData.value = res.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}
  
  const form: any = reactive({
    Recipient: '',
    CollectionDate: '',
    ApprovalStatus: '',
    Approver: '',
    pageIndex: 1,
    pageSize: 15,
    pageCount: 0,
    totalCount: 0,
    buttonArray: [],
    materialStoreId: '',
    title: "",
    usageDescription: "",
    materialRequisitNotes: "",
    approvalStatus: 10,
    materialRequisitionDtos: []
  })


//存储多选中的物资id
const multipleSelection:any = ref([]);
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
  
}
  
  //分页
  const handleSizeChange = (val: number) => {
    form.pageSize = val;
    getStoreList()
  }
  const handleCurrentChange = (val: number) => {
    form.pageIndex = val;
    getStoreList()
  }
  
  //物资领用列表
  const StoreData:any=ref([])
  const getStoreList = () => {
    axios.get('/mread/api/ShwoMaterialRequisition/GetMaterialRequisitionList', {
      params: {
        Recipient: form.Recipient,
        CollectionDate: form.CollectionDate,
        ApprovalStatus: form.ApprovalStatus,
        Approver: form.Approver,
        pageIndex: form.pageIndex,
        pageSize: form.pageSize,
      }
    }).then(res=>{
      console.log(res);
      StoreData.value = res.data.data.list;
      form.totalPage = res.data.data.pageCount;
      form.totalCount = res.data.data.totalCount;
    }).catch(err=>{
      console.log(err);
      
    })    
  }
  
  //重置
  const reset = () => {
    form.Recipient = '',
      form.CollectionDate = '',
      form.ApprovalStatus = '',
      form.Approver = '',
      form.pageIndex = 1,
      form.pageSize = 15,
      getStoreList()
  }
  
  //单删
  const del = (materialRequisitionId: number) => {
    ElMessageBox.confirm(
      '确认删除该物资领用申请吗?',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }
    )
      .then(() => {
        axios.post('/mwrite/api/MaterialRequisition/DeletedMaterialRequisition', {
          materialRequisitionId:materialRequisitionId
        }).then(res => {
          console.log(res);
          if (res.data.code > 0) {
            ElMessage.success("删除成功!")
            //刷新页面
            getStoreList()
          } else {
            ElMessage.error("删除失败!")
            return
          }
        }).catch(err => {
          console.log(err);
  
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消操作',
        })
      })
  }


  //批量删除
  const deletedRange = () => {
    let ids = multipleSelection.value.map((x: any) => x.materialRequisitionId);
  if (ids.length == 0) {
    ElMessage.error("请至少选择一条要删除的物资领用申请信息!")
    return
  }

  ElMessageBox.confirm(
    '确认删除这些物资领用申请吗?',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  )
    .then(() => {
      axios.post('/mwrite/api/MaterialRequisition/BatchDeletedMaterialRequisition', {
        materialRequisitionId: ids,
      }).then(res => {
        console.log(res);
        if (res.data.code > 0) {
          ElMessage.success("删除成功!")
          //刷新页面
          getStoreList()
        } else {
          ElMessage.error("删除失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
  }

//修改状态
const UpdateStatus = (materialRequisitionId: number, approvalStatus: number) => {
  let updateStatus: any = {
    materialRequisitionId: materialRequisitionId,
    approvalStatus: approvalStatus
  }
  axios.post('/mwrite/api/MaterialRequisition/UpdadteApprovalStatus',updateStatus).then(res=>{
    console.log(res);
    if (res.data.code > 0) {
      ElMessage.success("提交成功!")
      //刷新列表
      getStoreList()
    } else {
      ElMessage.error(res.data.message)
      return
    }
  }).catch(err=>{
    console.log(err);
    
  })    
  }

  //入库列表==>查询id
  const StoreIdData:any=ref([])
  const getStoreIdList = () => {
  
    axios.get('/mread/api/ShowMaterialStore/GetStoreList', {
      params: {
        pageIndex: form.pageIndex,
        pageSize: form.pageSize,
      }
    }).then(res=>{
      console.log(res);
      StoreIdData.value = res.data.data.list;
    }).catch(err=>{
      console.log(err);
      
    })    
  }

  //查看
  const checkInfo = (materialRequisitionId: number) => {
    centerDialogVisible.value = true
    getMaterialRequisitionById(materialRequisitionId)
    GetsotreDataList(materialRequisitionId)
  }

    //反填
    const getMaterialRequisitionById = (materialRequisitionId:number) => {
    axios.get('/mread//api/ShwoMaterialRequisition/ReverseMaterialRequisition', {
      params: {
        MaterialRequisitionId:materialRequisitionId
      }
    }).then(res=>{
    //console.log(res);
      let materialData: any = res.data.data;
      let materialRequisitionId:any =route.query.materialRequisitionId;
      form.title = materialData.title;
      form.usageDescription= materialData.usageDescription;
      form.materialRequisitNotes = materialData.materialRequisitNotes;
  }).catch(err=>{
    console.log(err);
    
  })    
  }


    //反填物品领用信息
  const sotreDataListByIdData: any = ref([])
  const GetsotreDataList = (materialRequisitionId:number) => {
    axios.get('/mread/api/ShwoMaterialRequisition/ReverseStorageMaterials?MaterialRequisitionId=' + materialRequisitionId).then(res => {
      //console.log(res);
      if (res.data.data.length > 0) {
        res.data.data.forEach((item: any) => {
        // 初始化 NumberArray
        NumberArray.value = res.data.data.map((item:any) => item.quantityReceived.toString());
        sotreDataListByIdData.value.push(item);
        // 如果需要，也可以为每个item设置数量，但这取决于您的具体需求
        // 例如，如果有一个特定的数组来存储数量，您可能需要按某种方式关联这些数量
      });
        form.materialStoreId = res.data.data[0].materialStoreId;
      }
  
    }).catch(err=>{
      console.log(err);
      
    })    
  }

  </script>
  
  <style scoped>
  
  </style>